
#import "RoomGalleryRoomViewController.h"
#import "GalleryLampHotspotView.h"

#define kHotspotMaxCount 3

@interface RoomGalleryRoomViewController () {
    BOOL _lampStates[kHotspotMaxCount];
    
}

@property (weak, nonatomic) IBOutlet UIView *imageContainerView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageWidthConstraint;
@property (weak, nonatomic) IBOutlet UIImageView *roomImage1;
@property (weak, nonatomic) IBOutlet UIImageView *roomImage2;
@property (weak, nonatomic) IBOutlet UILabel *roomNameLabel;

@property (strong, nonatomic) GalleryRoom *galleryRoom;
@property (strong, nonatomic) RoomGalleryViewController *roomGalleryViewController;
@property (strong, nonatomic) NSMutableArray *hotSpotViews;
@property (assign, nonatomic) BOOL showingRoomImage1;

@end

@implementation RoomGalleryRoomViewController

- (instancetype)initWithGalleryRoom:(GalleryRoom *)galleryRoom
          roomGalleryViewController:(RoomGalleryViewController *)roomGalleryViewController {
    NSAssert(galleryRoom.lamps.count <= kHotspotMaxCount, @"Out of bounds");

    self = [super init];
    if (self) {
        _galleryRoom = galleryRoom;
        _roomGalleryViewController = roomGalleryViewController;
        for (NSInteger i = 0; i < galleryRoom.lamps.count; i++) {
            _lampStates[i] = NO;
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.roomImage1.image = [self imageForLampState:_lampStates];
    self.roomImage2.alpha = 0;
    self.showingRoomImage1 = YES;
    
    self.roomNameLabel.text = self.galleryRoom.name;
}

-(void)viewDidLayoutSubviews {
    self.imageWidthConstraint.constant = self.view.frame.size.height * 16 / 9;
}

-(BOOL)toggleStateForLampAtIndex:(NSInteger)lampIndex {
    _lampStates[lampIndex] = !_lampStates[lampIndex];
    BOOL newStateIsOn = _lampStates[lampIndex];
    
    UIImageView *fromImageView = self.showingRoomImage1 ? self.roomImage1 : self.roomImage2;
    UIImageView *toImageView = self.showingRoomImage1 ? self.roomImage2 : self.roomImage1;

    self.showingRoomImage1 = !self.showingRoomImage1;

    toImageView.alpha = 0;
    toImageView.image = [self imageForLampState:_lampStates];
    [self.imageContainerView sendSubviewToBack:fromImageView];

    self.view.userInteractionEnabled = NO;
    [UIView animateWithDuration:newStateIsOn ? 0.2 : 0 animations:^{
        toImageView.alpha = 1;
    } completion:^(BOOL finished) {
        fromImageView.image = nil;
        self.view.userInteractionEnabled = YES;
    }];
    
    return newStateIsOn;
}

#pragma mark -

-(UIImage *)imageForLampState:(BOOL [])lampState {
    NSString *imageName;
    NSString *nameFormat = self.galleryRoom.imageNameFormat.lastPathComponent;
    if (self.galleryRoom.lamps.count == 2) {
        imageName = [NSString stringWithFormat:nameFormat, lampState[0], lampState[1]];
    } else {
        imageName = [NSString stringWithFormat:nameFormat, lampState[0], lampState[1], lampState[2]];
    }
    return [UIImage imageNamed:imageName];
}

- (void)roomViewWillAppear {
    self.roomNameLabel.alpha = 1;
    [self hideHotspots];
}

- (void)roomViewSelected {
    NSLog(@"roomViewSelected");
    if (!self.hotSpotViews) {
        [self.view layoutIfNeeded];
        [self addHotspotViewsToView];
        [self hideHotspots];
    }

    [self.roomGalleryViewController loadDocumentInRightInfoView:self.galleryRoom.documentName];
    [UIView animateWithDuration:.5 delay:.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.roomNameLabel.alpha = 0;
    } completion:^(BOOL finished) {
        [self showHotspots];
    }];
}

- (void)roomViewDeselected {
    NSLog(@"roomViewDeselected");
    [self hideHotspots];
}

-(void)addHotspotViewsToView {
    self.hotSpotViews = [NSMutableArray array];
    
    for (NSInteger i = 0; i < self.galleryRoom.lamps.count; i++) {
        GalleryRoomLamp *lamp = self.galleryRoom.lamps[i];
        CGSize size = self.imageContainerView.bounds.size;
        CGPoint point = CGPointMake(size.width * lamp.hotspotX, size.height * lamp.hotspotY);
        GalleryLampTapHandler infoTapHandler = ^{
            [self showDetailInfoForLamp:lamp];
        };
        GalleryLampHotspotView *hotspotView = [[GalleryLampHotspotView alloc] initWithCenterPoint:point
                                                                                   infoTapHandler:infoTapHandler];
        hotspotView.buttonInLeftCorner = lamp.hotspotX > 0.9;
        
        [self.hotSpotViews addObject:hotspotView];
        [self.imageContainerView addSubview:hotspotView];
        
        [hotspotView startAnimation];
    }
}

- (void)showHotspots {
    [UIView animateWithDuration:0.5 animations:^{
        for (UIView *view in self.hotSpotViews) {
            view.alpha = 1;
        }
    }];
}

- (void)hideHotspots {
    for (UIView *view in self.hotSpotViews) {
        view.alpha = 0;
    }
}

- (void)showDetailInfoForLamp:(GalleryRoomLamp *)galleryRoomLamp {
    [self.roomGalleryViewController showDocumentInTopInfoView:galleryRoomLamp.documentName];
}

#pragma mark - Actions

- (IBAction)imageTapped:(UITapGestureRecognizer *)tapRecognizer {
    CGPoint touchPoint = [tapRecognizer locationInView:self.imageContainerView];
    touchPoint.x /= self.imageContainerView.frame.size.width;
    touchPoint.y /= self.imageContainerView.frame.size.height;
    
    __block NSInteger nearestIdx = 0;
    __block CGFloat nearestDist = CGFLOAT_MAX;
    [self.galleryRoom.lamps enumerateObjectsUsingBlock:^(GalleryRoomLamp *lamp, NSUInteger idx, BOOL *stop) {
        CGFloat dx = lamp.hotspotX - touchPoint.x;
        CGFloat dy = lamp.hotspotY - touchPoint.y;
        CGFloat dist = sqrt(dx * dx + dy * dy);
        if (dist < nearestDist) {
            nearestIdx = idx;
            nearestDist = dist;
        }
    }];
    
    [self tappedHotspotAtIndex:nearestIdx];

    NSLog(@"%@", [NSValue valueWithCGPoint:touchPoint]);
    NSLog(@"%ld, %f", (long)nearestIdx, nearestDist);
}

-(void)tappedHotspotAtIndex:(NSInteger)idx {
    GalleryLampHotspotView *hotspotView = self.hotSpotViews[idx];
    BOOL newStateIsOn = [self toggleStateForLampAtIndex:idx];
    if (newStateIsOn) {
        [hotspotView showInfoButton];
    } else {
        [hotspotView showHotspot];
    }
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
